package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.GeoValidationMethod;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.GeoDistanceSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;




@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    RestHighLevelClient client;

    int i = 1;
    int j = 1;
    @Override
    public PageResult query(RequestParams requestParams) {
        try {
            //1.准备Request
            SearchRequest request = new SearchRequest("hotel");
            //2.准备DSL语句
            //2.1 query,添加了其他的条件,抽取出来直接引用
            buildBasicQuery(requestParams, request);
            //2.2 分页
            Integer page = requestParams.getPage();
            Integer size = requestParams.getSize();
            request.source().from((page - 1) * size).size(size);//得到分页的数据
            //3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //4.解析响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void buildBasicQuery(RequestParams requestParams, SearchRequest request) {
        //1.构建BooleanQuery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //2.关键字搜索
        String key = requestParams.getKey();//获得前台传来的搜索框的数据
        if (key == null || "".equals(key)) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());//如果没没有传入数据或传入的是空字符,那么查询所有数据返回前端
        } else if (key.equals("附近"))
        {
            boolQueryBuilder.must(QueryBuilders.geoDistanceQuery("location")
                    .distance("15", DistanceUnit.KILOMETERS)
                    .point(31.03, 121.61));
            //按照距离排序,改地点内15km由近到远--
            GeoDistanceSortBuilder distanceSort = SortBuilders.geoDistanceSort("location", 31.03, 121.61);
            distanceSort.order(SortOrder.ASC);
            distanceSort.geoDistance(GeoDistance.ARC);
            distanceSort.unit(DistanceUnit.KILOMETERS);
            distanceSort.validation(GeoValidationMethod.STRICT);

            request.source().sort(distanceSort);
        } else {
            // 2.2.高亮
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));//若传入了数据,则按照此数据进行查询
        }
        //3.品牌条件
        String brand = requestParams.getBrand();//获得前端传入的品牌数据
        if (brand != null && !"".equals(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));//只有当前端有传入品牌数据且不为空值时,才会进行过滤
        }
        //4.城市条件
        String city = requestParams.getCity();//获得前端传入的城市数据
        if (city != null && !"".equals(city)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", city));//只有当前端有传入城市数据且不为空值时,才会进行过滤
        }
        //5.星级条件
        String starName = requestParams.getStarName();//同上过滤星级
        if (starName != null && !"".equals(starName)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", starName));
        }
        //6.价格条件
        Integer minPrice = requestParams.getMinPrice();//同上设置价格,用rangeQuery限定最高和最低价
        Integer maxPrice = requestParams.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
        }

        // 2.算分控制
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQueryBuilder,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });

        // 7.放入source,一定要放入,不然等于无条件进行查询
        request.source().query(functionScoreQuery);


        //按钮排序
        //1.价格排序
        if(requestParams.getSortBy().equals("price")){
            if(i%2==0){
                request.source().sort("price",SortOrder.ASC);
            }else {
                request.source().sort("price",SortOrder.DESC);
            }
            i++;

        }
        //2.评分排序
        if(requestParams.getSortBy().equals("score")){
            if(i%2==0){
                request.source().sort("score",SortOrder.ASC);
            }else {
                request.source().sort("score",SortOrder.DESC);
            }
            j++;
        }
    }


    //结果解析
    private PageResult handleResponse(SearchResponse response) {
        //4.解析响应
        SearchHits searchHits = response.getHits();
        //4.1获取总条数
        long total = searchHits.getTotalHits().value;
        //4.2文档数组
        SearchHit[] hits = searchHits.getHits();
        //4.3遍历
        List<HotelDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            //获取文档source
            String json = hit.getSourceAsString();
            //反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            // 获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                // 根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    // 获取高亮值
                    String name = highlightField.getFragments()[0].string();
                    // 覆盖非高亮结果
                    hotelDoc.setName(name);
                }
            }
            //获取排序值
            Object[] sortValues = hit.getSortValues();
            if(sortValues.length>0){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            //放入集合
            hotels.add(hotelDoc);
        }
        //4.4封装返回
        return new PageResult(total, hotels);
    }
}
